<!-- 企业信息 - 供应商 - 编辑查看组件 -->
<script setup lang='ts'>
import { useAddorDelStock, useEditEnterprise, useGetBuyerPage } from '@fl/api/man-api'
import { useGetSupplierStockLabel } from '@fl/api/purchase'
import FlUpload from '@fl/components/fl-upload.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { useUserStore } from '@fl/store/modules/user'
import { provide, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import ApplyInfo from './apply-info.vue'
import { name, tabs } from './constant'
import CustomerInfo from './customer-info.vue'
import FactoryInfo from './factory-info.vue'
import FirmInfo from './firm-info.vue'

defineOptions({ name })
const { createMessage } = useMessage()
const userStore = useUserStore()

const { meta: { isAdmin }, query } = useRoute()
const { go } = useRouter()

provide('id', query.id)
provide('supplierId', query.supplierId)
provide('secondType', query.secondType)
provide('type', query.type)
provide('supplierName', query.supplierName)

const buyerParams = computed(() => {
    if (isAdmin) {
        return {
            name: '',
            page: 1,
            size: 99999,
        }
    }
    return {
        supplierName: '',
    }
})
const { data: buyerDate } = isAdmin ? useGetBuyerPage(buyerParams) : useGetSupplierStockLabel()
const buyerList = computed(() => {
    return isAdmin
        ? (buyerDate.value?.records?.map((item: any) => ({ label: item.enterpriseName, value: item.id })) || [])
        : (buyerDate.value?.map((item: any) => ({ label: item.supplierName, value: item.supplierId })) || [])
})

const activeTab = ref(1)
const applyRef = ref()
const formRef = ref()
const addDiglog = ref(false)

const addForm = ref<any>({ buyerId: '', file: [], operateName: '', wareHouseName: query?.supplierName ?? '' })
const addCol = [
    {
        label: '入库供应商',
        prop: 'wareHouseName',
        valueType: 'text',
    },
    {
        label: '采购商',
        options: buyerList.value,
        prop: 'buyerId',
        valueType: 'select',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 2000,
            showWordLimit: true,
        },
        label: '供应商入库说明',
        prop: 'remark',
        valueType: 'textarea',
    },
    {

        label: '附件',
        prop: 'file',
    },
    {
        label: '操作人',
        prop: 'operateName',
        valueType: 'text',
    },
]
const rules = {
    buyerId: [
        {
            message: '请选择供应商',
            required: true,
        },
    ],
    remark: [
        {
            message: '请输入说明',
            required: true,
        },
    ],
}

addForm.value.operateName = userStore.getUserInfo?.sysUser?.userName || ''

const { mutate } = useEditEnterprise()
function doSubmit() {
    mutate(applyRef.value.getParams(), {
        onError(error) {
            console.log('🚀 ~ onError ~ error:', error)
        },
        onSuccess: () => {
            createMessage.success('操作成功')
            go(-1)
        },
    })
}

const { mutate: addOrDelStockMutate } = useAddorDelStock()
async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            supplierId: query.supplierId,
            ...addForm.value,
            file: JSON.stringify(addForm.value.file),
            type: '入库',
        }
        Reflect.deleteProperty(params, 'operateName')
        addOrDelStockMutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                addDiglog.value = false
                go(-1)
            },
        })
    }
}
</script>

<template>
    <ElCard shadow="never">
        <div class="mb-20 text-20 font-600 flex items-center">
            <span>{{ query?.supplierName ?? '' }}</span>

            <!-- <span class="px-10 py-2 ml-10 bg-#ffa7a7 text-13 c-#fff">企业风险：8</span> -->
        </div>

        <p class="py-2 text-13 c-#333">
            机构类型：{{ query?.typeName ?? '' }} &nbsp;&nbsp;|&nbsp;&nbsp;来源：{{ query?.sourceName ?? '' }}
        </p>

        <el-tabs v-model="activeTab">
            <el-tab-pane v-for="tab in tabs"
                         :key="tab.value"
                         :label="tab.label"
                         :name="tab.value"
            />
        </el-tabs>

        <ApplyInfo v-if="activeTab === 1"
                   ref="applyRef"
        />

        <FirmInfo v-if="activeTab === 2" />

        <FactoryInfo v-if="activeTab === 3" />

        <CustomerInfo v-if="activeTab === 4" />

        <div class="my-20 text-center w-full">
            <el-button @click="() => go(-1)">
                返回
            </el-button>

            <template v-if="query.type === 'edit'">
                <el-button v-if="activeTab === 1"
                           type="primary"
                           @click="doSubmit"
                >
                    提交
                </el-button>

                <el-button v-else
                           type="primary"
                           @click="() => addDiglog = true"
                >
                    入库
                </el-button>
            </template>
        </div>
    </ElCard>

    <!-- 供应商入库 -->
    <PlusDialogForm ref="formRef"
                    v-model:visible="addDiglog"
                    v-model="addForm"
                    title="入库"
                    width="800"
                    :form="{ columns: addCol, rules, labelWidth: 140 }"
                    @confirm="confirm"
    >
        <template #plus-field-file>
            <FlUpload v-model="addForm.file"
                      is-mall-admin
                      list-type="text"
                      :limit="10"
                      accept="*"
            />
        </template>
    </PlusDialogForm>
</template>
